<template>
  <div class="home-layout">
    <aside class="sidebar">
      <h1>风行旅途</h1>
      <hr class="sidebar-divider" />
      <nav>
        <ul>
          <li>
            <a href="#" :class="{ active: activeTab === 'train' }" @click.prevent="setActive('train')">火车购票</a>
          </li>
          <li>
            <a href="#" :class="{ active: activeTab === 'meal' }" @click.prevent="setActive('meal')">火车餐</a>
          </li>
          <li>
            <a href="#" :class="{ active: activeTab === 'hotel' }" @click.prevent="setActive('hotel')">酒店</a>
          </li>
        </ul>
      </nav>
    </aside>
    <header class="header">
      <div style="margin-right: auto;">{{ displayName }},欢迎您！</div>
      <div class="header-nav">
        <a href="#" @click.prevent="goToHistoryOrder">历史订单</a>
        <a href="#" @click.prevent="goToMessages">消息中心</a>
        <a href="https://gitee.com/wangzi-ma/software-engineering-homework" target="_blank">关于我们</a>
      </div>
      <div class="avatar-wrapper">
        <img class="avatar" src="/logo.png" alt="头像" />
        <ul class="dropdown-menu">
          <li><a href="#" @click.prevent="goToPersonalCenter">个人中心</a></li>
          <li><a href="#" @click.prevent="goToWallet">我的钱包</a></li>
          <li><a href="#" @click.prevent="logout">退出登录</a></li>
        </ul>
      </div>
    </header>
    <main class="main-content">
      <!-- 主体内容留空 -->
      <div class="background-image"></div> <!-- 背景图层 -->
      <div class="ticket-box">
        <form class="ticket-form">
          <div class="form-group">
            <label for="from">出发城市</label>
            <input v-model="fromCity" type="text" id="from" placeholder="请输入出发城市" @focus="showFromDropdown = true; showToDropdown = false" />
            <ul class="city-dropdown" v-if="showFromDropdown">
              <li v-for="city in cities" :key="city" @click="selectCity('from', city)">{{ city }}</li>
            </ul>
          </div>
          <div class="form-group">
            <label for="to">目标城市</label>
            <input v-model="toCity" type="text" id="to" placeholder="请输入目标城市" @focus="showToDropdown = true; showFromDropdown = false" />
            <ul class="city-dropdown" v-if="showToDropdown">
              <li v-for="city in cities" :key="city" @click="selectCity('to', city)">{{ city }}</li>
            </ul>
          </div>
          <div class="form-group">
            <label for="date">选择日期</label>
            <input v-model="date" type="date" id="date" />
          </div>
          <button type="button" @click="handleQuery">查询</button>
        </form>
      </div>
    </main>
  </div>
</template>

<script setup lang="ts">
import { useRouter } from 'vue-router'
import { ref, onMounted, onBeforeUnmount } from 'vue'

const router = useRouter()
const activeTab = ref('train') // 默认激活“火车购票”
const displayName = ref('')
const fromCity = ref('')
const toCity = ref('')
const date = ref('')
/*所有可供选择的城市*/
const cities = [
  '北京', '上海', '天津', '重庆',
  '合肥', '杭州', '福州', '广州', '南宁', '海口',
  '石家庄', '太原', '呼和浩特', '沈阳', '长春', '哈尔滨',
  '郑州', '武汉', '长沙', '南京', '济南', '南昌',
  '成都', '贵阳', '昆明', '西安', '兰州', '西宁',
  '拉萨', '银川', '乌鲁木齐'
].sort((a,b) => a.localeCompare(b,'zh', { sensitivity: 'base' }));
const showFromDropdown = ref(false)
const showToDropdown = ref(false)

function handleQuery() { /*查询线路逻辑 */
  if (!fromCity.value || !toCity.value || !date.value) {
    alert('请输入完整信息')
    return
  }
  // 检查日期是否在七天范围内
  const selectedDate = new Date(date.value);
  const today = new Date();
  today.setHours(0, 0, 0, 0); // 清除时分秒，确保对比准确
  const maxDate = new Date(today);
  maxDate.setDate(today.getDate() + 7); // 允许查询7天内（包括今天）
  if (selectedDate > maxDate || selectedDate < today) {
    alert('只能查询7天内的车次信息');
    return;
  }
  // 合法，跳转页面
  router.push({
    path: '/train-list',
    query: {
      from: fromCity.value,
      to: toCity.value,
      date: date.value
    }
  })
}
function selectCity(type: 'from' | 'to', city: string) {
  if (type === 'from') {
    fromCity.value = city
    showFromDropdown.value = false
  } else {
    toCity.value = city
    showToDropdown.value = false
  }
}
function handleClickOutside(event: MouseEvent) {
  // 延迟执行，确保点击 <li> 事件先触发
  setTimeout(() => {
    const target = event.target as HTMLElement
    if (!target.closest('.city-dropdown') && !target.closest('#from') && !target.closest('#to')) {
      showFromDropdown.value = false
      showToDropdown.value = false
    }
  }, 0)
}
onMounted(() => {
  displayName.value = localStorage.getItem('username') || '';
  document.addEventListener('mousedown', handleClickOutside);
});
onBeforeUnmount(() => document.removeEventListener('mousedown', handleClickOutside))

function goToHistoryOrder(){
  router.push({
    path: '/history',
    query: {username: displayName.value}
  });
}
function goToMessages() {
  router.push({
    path: '/messages',
    query: {username: displayName.value}
  });
}
function goToWallet() {
  // 跳转到钱包页面并传递昵称参数
  router.push({
    path: '/wallet', // 钱包页面路由路径
    query: { username: displayName.value } // 传递参数
  });
}
function goToPersonalCenter(){
  router.push({
    path: '/center',
    query: {username: displayName.value}
  });
}
function logout() { /*退出登录 */
  // 可添加清除登录状态的逻辑，例如 localStorage 清理 token
  localStorage.removeItem('username')
  router.push('/login')
}
function setActive(tab: string) { /*导航栏跳转*/
  activeTab.value = tab
  if (tab === 'hotel') {
    router.push('/hotel') // 跳转到酒店页面
  } else if (tab === 'train') {
    router.push('/home') // 当前页可写死或省略
  } else if (tab === 'meal') {
    router.push('/meal') // 当前页可写死或省略
  }
  /*else if (tab === 'history') {
    router.push('/history') // 将来你可以加这个页面
  }*/
}
</script>

<style scoped>
/* 添加重置样式 */
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
html, body {
  height: 100%;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}
/* 容器布局 */
.home-layout {
  display: grid;
  grid-template-columns: 200px 1fr;
  transition: grid-template-columns 0.3s ease;
  grid-template-rows: 60px 1fr;
  grid-template-areas:
    "sidebar header"
    "sidebar main";
  height: 100vh;
  width: 100vw; /* 保证横向占满 */
}
.home-layout.collapsed {
  grid-template-columns: 60px 1fr;
}
/* 左侧边栏 */
.sidebar {
  grid-area: sidebar;
  background-color: #0086f6;
  color: white;
  padding: 20px;
  box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  transition: width 0.3s ease;
  overflow: hidden;
  position: relative;
}
/* 分隔线样式 */
.sidebar-divider {
  border: none;
  border-top: 1px solid rgba(255, 255, 255, 0.3);
  /*margin: 10px 0 20px;*/
  margin: 8px 0 16px;
}
/* 调整导航项间距和分隔 */
.sidebar li + li {
  border-top: 1px solid rgba(255, 255, 255, 0.15); /* 每项之间加线 */
  padding-top: 10px;
  margin-top: 8px;
}
/* 标题 */
.sidebar h1 {
  font-size: 28px;
  margin-bottom: 20px;
  text-align: center;
}
/* 导航样式 */
.sidebar ul {
  list-style: none;
  padding: 0;
  width: 100%;
}
.sidebar li {
  margin: 8px 0;
}
.sidebar a {
  display: flex;
  align-items: center;
  gap: 10px;
  color: white;
  padding: 10px;
  border-radius: 6px;
  text-decoration: none;
  transition: background-color 0.2s ease;
}
.sidebar a:hover {
  background-color: rgba(255, 255, 255, 0.1);
}
.sidebar a.active {
  background-color: rgba(255, 255, 255, 0.25);
  font-weight: bold;
}

/* 右上角头部 */
.header {
  grid-area: header;
  display: flex;
  justify-content: space-between; /* 左右分开 */
  align-items: center;
  padding: 0 20px;
  background-color: #f0f0f0;
  border-bottom: 1px solid #ddd;
}
.header-nav {
  display: flex;
  margin-right: 20px;
}
.header-nav a {
  margin-right: 20px;
  color: #333;
  text-decoration: none;
}
.header-nav a:hover {
  text-decoration: underline;
}
/* 头像 */
.avatar-wrapper {
  position: relative;
  display: inline-block;
  cursor: pointer;
  padding-top: 10px; /* 保证 hover 区域连贯 */
}
.avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  object-fit: cover; /* 防止图片变形，裁剪填充 */
  transition: box-shadow 0.3s;
}
.avatar:hover {
  box-shadow: 0 0 8px rgba(0, 134, 246, 0.5);
}
/* 头像下拉菜单样式 */
.dropdown-menu {
  position: absolute;
  top: 100%;
  right: 0;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  list-style: none;
  padding: 10px 0;
  margin: 0;
  min-width: 140px;
  display: none;
  z-index: 100;
}
.dropdown-menu li {
  padding: 10px 20px;
}
.dropdown-menu li a {
  text-decoration: none;
  color: #333;
  display: block;
  transition: background 0.2s;
}
.dropdown-menu li:hover {
  background-color: #f0f0f0;
}
/* 显示菜单：鼠标悬停时 */
.avatar-wrapper:hover .dropdown-menu {
  display: block;
}

/* 中间内容 */
.main-content {
  grid-area: main;
  display: flex;
  justify-content: center;
  align-items: flex-start; /* 顶部对齐，然后靠 margin 推一点 */
  padding: 20px;
  overflow-y: auto;
  min-height: calc(100vh - 60px); /* 减去 header 高度 */
  position: relative; /* 让背景图层相对于它定位 */
}
/* 背景图片 */
.background-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 320px;
  min-height: 300px; /* 根据图片比例设置 */
  background-image: url('/background.jpg'); /* 替换为实际图片 URL */
  background-repeat: no-repeat;
  background-size: cover; /* 或 contain，视图片效果而定 */
  background-position: center 65%;
  z-index: 0; /* 确保在内容底下 */
}
/* 火车票表单 */
.ticket-box {
  background-color: #fff;
  border-radius: 10px;
  padding: 35px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  max-width: 1000px;
  margin: 200px auto; /* 居中并离顶部远一点 */
  width: 100%; /* 可选：让其在最大宽度内尽可能填满 */
  position: relative;
  z-index: 1;
  min-height: 200px; /* ✅ 新增或修改：让整个框更高 */
  display: flex;
  flex-direction: column;
  justify-content: center; /* 内容垂直居中 */
}
.ticket-box h2 {
  margin-bottom: 20px;
  font-size: 26px;
  color: #333;
}
.ticket-form {
  display: flex;
  flex-direction: row; /* 横向排列 */
  gap: 15px;
  flex-wrap: wrap; /* 如果屏幕不够自动换行 */
  align-items: flex-end; /* 对齐到输入框底部 */
}
.form-group {
  display: flex;
  flex-direction: column;
  flex: 1; /* 平均占位 */
  min-width: 120px;
  gap: 20px; /* 增加 label 和 input 的统一间距 */
}
.form-group label {
  margin-bottom: 5px;
  font-weight: bold;
  font-size: 20px;
  color: #000; /* 比较柔和的灰色 */
  padding-left: 5px; /* 轻微缩进 */
}
/*输入框*/
.form-group input {
  padding: 16px 14px;
  font-size: 18px;     /* 增大字体 */
  border: 1px solid #ccc;
  border-radius: 6px;
  background-color: #f9f9f9; /* ✅ 添加：浅灰背景 */
  color: #333;
}
.ticket-form button {
  white-space: nowrap; /* 防止按钮内容换行 */
  padding: 0 30px;
  height: 56px; /* 高度略加 */
  line-height: 24px;        /* 使文字垂直居中 */
  background-color: #0086f6;
  color: white;
  border: none;
  border-radius: 10px; /* 圆角更柔和 */
  cursor: pointer;
  font-size: 20px;
  box-shadow: 0 2px 5px rgba(0, 134, 246, 0.2); /* 添加按钮阴影 */
}
.ticket-form button:hover {
  background-color: #0075d9;
  box-shadow: 0 4px 10px rgba(0, 134, 246, 0.3); /* 悬浮时阴影更深 */
}
/*城市选择*/
.city-dropdown {
  position: absolute;
  background: white;
  border: 1px solid #ddd;
  border-radius: 8px;
  max-height: 200px;
  overflow-y: auto;
  margin-top: 120px;
  z-index: 10;
  width:200px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
}
.city-dropdown li {
  padding: 10px 15px;
  cursor: pointer;
  transition: background 0.2s;
}
.city-dropdown li:hover {
  background-color: #f0f0f0;
}

</style>
